from optparse import OptionParser
import codecs
import os.path
import shutil


class DictTool(object):
    def __init__(self, builddir):
        self.builddir = builddir
        self.modified = False
        self.loaded = False

    def checkLoaded(self):
        if self.loaded:
            return
        self.loaded = True
        self.modified = False
        self.metainfo = dict()
        self.metacomments = []
        path_to_meta = os.path.join(self.builddir,
                                    'dictionaries.meta')
        if not os.path.isfile(path_to_meta):
            self.metacomments.append(
                '# File name, Description, enable by default')
            return
        meta_file = codecs.open(path_to_meta, encoding='utf-8', mode='r')
        for line in meta_file:
            line = line.strip()
            if line.startswith('#'):
                self.metacomments.append(line)
                continue
            info = {'file': '', 'desc': '', 'default': 'false'}
            (info['file'], info['desc'], info['default']) = line.split(',')
            self.metainfo[info['file'].strip()] = info
        meta_file.close()

    def saveIfNecessary(self):
        if self.modified:
            pass
        path_to_meta = os.path.join(self.builddir,
                                    'dictionaries.meta')
        meta_file = codecs.open(path_to_meta, encoding='utf-8', mode='w')

        for line in self.metacomments:
            meta_file.write(line)
            meta_file.write('\n')
        for key in sorted(self.metainfo.keys()):
            info = self.metainfo[key]
            meta_file.write('%s, %s, %s\n'
                            % (key, info['desc'], info['default']))
        meta_file.close()
        self.modified = False
        self.loaded = False
        del self.metainfo
        del self.metacomments

    def maybeAddFile(self, languages, filename):
        self.checkLoaded()
        meta_file = codecs.open(filename, encoding='utf-8', mode='r')
        file_meta = dict()
        for line in meta_file:
            line = line.strip()
            if line.startswith('#'):
                continue
            if len(line) == 0:
                continue
            (key, value) = line.split('=')
            file_meta[key.strip()] = value.strip()
        meta_file.close()

        if file_meta['file'] in self.metainfo:
            print 'File %s already exist' % (file_meta['file'],)
            return
        if languages is not None and file_meta['lang'] not in languages:
            print 'File %s has language %s - skipping' % \
                  (file_meta['file'], file_meta['lang'])
        self.modified = True
        self.metainfo[file_meta['file']] = file_meta

        src_dir = os.path.dirname(filename)
        shutil.copy(os.path.join(src_dir, file_meta['file']),
                    os.path.join(self.builddir, file_meta['file']))

if __name__ == '__main__':
    parser = OptionParser()
    parser.add_option(
        '-l', '--language', dest='language', action='append',
        help='work only with LANG dictionaries', metavar='LANG')
    parser.add_option(
        '-b', '--builddir', dest='builddir', default='.',
        help='build directory where dictionaries will be stored.')
    (opt, args) = parser.parse_args()
    if not hasattr(opt, 'language'):
        opt.language = []
    tool = DictTool(opt.builddir)
    for filename in args:
        tool.maybeAddFile(opt.language, filename)
    tool.saveIfNecessary()
